<template>
  <div class="app-container">
    <el-form
      :model="oilAndGunQuery"
      ref="oilAndGunQuery"
      :inline="true"
      v-show="showSearch"
      class="globalSerchFormStyle"
    >
      <el-row>
        <el-col :span="6" v-if="$store.state.user.userLevel === null">
          <el-form-item label="油企名称" prop="enterpriseName">
            <el-input
              v-model="oilAndGunQuery.enterpriseName"
              placeholder="请输入油企名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
        <el-col
          :span="6"
          v-if="[null, '1'].includes($store.state.user.userLevel)"
        >
          <el-form-item label="油站名称" prop="stationName">
            <el-input
              v-model="oilAndGunQuery.stationName"
              placeholder="请输入油站名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="global_el_rowStyle">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          type="primary"
          plain
          >重置</el-button
        >
      </el-col>
      <el-col :span="1.5" v-if="$store.state.user.userLevel === '1'">
        <el-button plain size="mini" @click="oneClickAdjustment"
          >一键调价</el-button
        >
      </el-col>
    </el-row>
    <el-table
      stripe
      :data="oilAndGunList"
      style="width: 100%"
      v-loading="oilAndGunLoading"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        prop="enterpriseName"
        label="油企名称"
        align="left"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="stationName"
        label="油站名称"
        align="left"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column prop="oilClass" label="类型" align="left">
      </el-table-column>
      <el-table-column prop="oilName" label="品号" align="left">
      </el-table-column>
      <el-table-column prop="oilType" label="型号" align="left">
      </el-table-column>
      <el-table-column prop="gunNameList" label="枪号" align="left">
        <template slot-scope="scope">
          {{
            !!scope.row.gunNameList && scope.row.gunNameList.length > 0
              ? scope.row.gunNameList + "号枪"
              : ""
          }}
        </template>
      </el-table-column>
      <el-table-column
        prop="oilOfficialPrice"
        label="发改委价(元/L)"
        align="left"
      >
        <template slot-scope="scope">
          {{
            scope.row.oilOfficialPrice == null
              ? "未设置"
              : scope.row.oilOfficialPrice
          }}
        </template>
      </el-table-column>
      <el-table-column prop="oilStationPrice" label="当前油站价(元/L)" align="left">
        <template slot-scope="scope">
          {{
            scope.row.oilStationPrice == null
              ? "未设置"
              : scope.row.oilStationPrice
          }}
        </template>
      </el-table-column>
      <el-table-column
        prop="discountPrice"
        label="优惠价(元/L)（仅展示用）"
        align="left"
      >
        <template slot-scope="scope">
          {{
            scope.row.discountPrice == null ? "未设置" : scope.row.discountPrice
          }}
        </template>
      </el-table-column>
      <el-table-column prop="preEffectivePrice" label="预约生效价(元/L)"  align="left">
      </el-table-column>
      <el-table-column
        prop="effectDate"
        label="生效时间"
        align="left"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="updatedTime"
        label="最后一次修改时间"
        align="left"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column label="操作" align="left">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleOilAndGunEdit(scope.row)"
            size="mini"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      :hidden="oilAndGunListTotal > 0 ? false : true"
      :total="oilAndGunListTotal"
      :page.sync="oilAndGunQuery.pageNum"
      :limit.sync="oilAndGunQuery.pageSize"
      @pagination="getOilAndGunList"
      :autoScroll="true"
    />

    <!-- 添加油企 -->
    <el-dialog
      :title="'设置价格'"
      :visible.sync="oilAndGunFormOpen"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="oilAndGunForm"
        :model="oilAndGunForm"
        :rules="rules"
        label-width="80px"
        label-position="top"
      >
        <el-row>
          <el-col :span="23">
            <el-form-item
              label="发改委价(元/L)"
              prop="oilOfficialPrice"
              :rules="{
                required: true,
                message: '请填写发改委价',
                trigger: 'change',
              }"
            >
              <el-input
                v-model="oilAndGunForm.oilOfficialPrice"
                placeholder="请输入发改委指导价"
              />
            </el-form-item>
          </el-col>

          <el-col :span="23">
            <el-form-item
              label="油站价"
              prop="oilStationPrice"
              :rules="{
                required: true,
                message: '请填写油站价',
                trigger: 'change',
              }"
            >
              <el-input
                v-model="oilAndGunForm.oilStationPrice"
                placeholder="请输入油站价"
              />
            </el-form-item>
          </el-col>
          <el-col :span="23">
            <el-form-item label="优惠价(元/L)（仅展示用）" prop="discountPrice">
              <el-input
                v-model="oilAndGunForm.discountPrice"
                placeholder="请输入油站价"
              />
            </el-form-item>
          </el-col>
          <el-col :span="23">
            <el-form-item label="生效日期" prop="effectDate" >
              <div>
                  <el-checkbox v-model="oilAndGunForm.effectDateStatus" @change="effecgDateChange">立即生效</el-checkbox>
              </div>
              <el-date-picker
                    v-model="effectDay"
                    align="right"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期"
                    style="margin-right: 10px;"
                  >
                  </el-date-picker>
                  <el-time-select
                    v-model="effectTime"
                    :picker-options="{
                      start: '00:00',
                      step: '01:00',
                      end: '23:00'
                    }"
                    placeholder="选择时间点">
                  </el-time-select>
              <!-- <el-date-picker
                style="width: 100%"
                v-model="oilAndGunForm.effectDate"
                type="datetime"
                placeholder="选择日期"
                format="yyyy-MM-dd HH:00:00"
                value-format="yyyy-MM-dd HH:00:00"
              >
              </el-date-picker> -->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="oilAndGunSubmitForm"
          >确 定</el-button
        >
        <el-button size="mini" @click="oilAndGunCancel">取 消</el-button>
      </div>
    </el-dialog>
    <oilPrice :parm="params" ref="oilPriceForm" @successData="successData" />
  </div>
</template>

<script>
import { formatDate } from '@/utils/index'

import {
  listDept,
  getDept,
  delDept,
  addDept,
  updateDept,
  listDeptExcludeChild,
  listTree,
  setMnoSplit,
} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { regionData } from "element-china-area-data";
import { getToken } from "@/utils/auth";
import { addOilAndGun, upOilAndGun, getOilAndGunList } from "@/api/dept";
import oilPrice from "./Dept_OilPrice-form.vue";

export default {
  name: "Dept",
  components: { Treeselect, oilPrice },
  data() {
    var validateDate = (rule, value,callback) => {

        const now = formatDate(new Date())
        const str = now.split(' ')
        const day = str[0]
        const time = str[1].substring(0,2) + ':00'
        if(day > this.effectDay) {
          return callback(new Error('生效日期不能小于当前日期'))
        }
         if(day === this.effectDay) {
          if(time >= this.effectTime) {
            return callback(new Error('生效时间不能小于当前时间'))
          }
        }
        callback()
      };
    return {
      effectDateStatus: '',
      effectDay: '',
      effectTime: '',
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 弹出层标题
      title: "",

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        effectDate: [
          { required: true, validator:validateDate  , trigger: 'change' }
                ]
      },
      oilAndGunForm: {},
      oilAndGunFormOpen: false,
      payListOpen: true,
      payList: [{}],
      payConfForm: {
        type: "1",
      },
      payConfOpen: false,

      oilAndGunList: [],
      oilAndGunLoading: false,
      oilAndGunListTotal: 0,
      oilTankList: [{}],
      oilTankListOpen: false,
      oilTankConfOpen: false,
      oilAndGunQuery: {
        pageSize: 10,
        pageNum: 1,
      },
      params: {},
    };
  },
  created() {
    this.getOilAndGunList();
  },
  methods: {
    formatter(thistime, fmt) {
            let $this = new Date(thistime)
            let o = {
                'M+': $this.getMonth() + 1,
                'd+': $this.getDate(),
                'h+': $this.getHours(),
                'm+': $this.getMinutes(),
                's+': $this.getSeconds(),
                'q+': Math.floor(($this.getMonth() + 3) / 3),
                'S': $this.getMilliseconds()
            }
            if (/(y+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, ($this.getFullYear() + '').substr(4 - RegExp.$1.length))
            }
            for (var k in o) {
                if (new RegExp('(' + k + ')').test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
                }
            }
            return fmt
        },
    effecgDateChange(val) {
            if (val) {
                // this.oilsForm.effectDate = this.formatter(new Date(), 'yyyy-MM-dd hh:mm:ss');
                const now = new Date()
                this.effectDay = this.formatter(now, 'yyyy-MM-dd');
                // const time = new Date(now.getTime() + 60 * 60 * 1000)
                this.effectTime = this.formatter(now, 'hh:mm')

            }
        },
    successData() {
      this.params = {
        drawerShow: false,
      };
      this.getOilAndGunList();
    },
    oneClickAdjustment() {
      this.params = {
        drawerShow: true,
      };
      this.$refs.oilPriceForm.getListByEnterprise();
      this.$refs.oilPriceForm.clearData();
    },
    getOilAndGunList() {
      this.oilAndGunLoading = true;
      getOilAndGunList(this.oilAndGunQuery)
        .then((res) => {
          console.log(res);
          if (res.rows == null) {
            this.oilAndGunList = [];
            this.oilAndGunListTotal = 0;
          }
          this.oilAndGunList = res.rows;
          // 给列表中每项都添加一个立即生效字段
          this.oilAndGunList.forEach(obj => {
            obj.effectDateStatus = false
          })
          this.oilAndGunListTotal = res.total;
        })
        .finally(() => (this.oilAndGunLoading = false));
    },
    handleOilTankListOpen() {
      this.oilTankListOpen = true;
    },

    handleOilAndGunEdit(row) {
      this.oilAndGunForm = JSON.parse(JSON.stringify(row))
      this.effectDay = ''
      this.effectTime = ''
      this.oilAndGunFormOpen = true;
      this.$nextTick(() => {
        this.$refs.oilAndGunForm.clearValidate()

      })
    },
    handleChangeRegionData(value) {
      console.log(this.form.regionData);
      console.log(this.form);
    },
    // 取消按钮
    oilAndGunCancel() {
      this.oilAndGunFormOpen = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getOilAndGunList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("oilAndGunQuery");
      this.handleQuery();
    },

    oilAndGunSubmitForm: function () {
      this.$refs["oilAndGunForm"].validate((valid) => {
        if (valid) {
          console.log(this.oilAndGunForm);
          this.oilAndGunForm.effectDate = this.effectDay + ' ' + this.effectTime + ':00'
          upOilAndGun(this.oilAndGunForm).then((res) => {
            this.getOilAndGunList();
            this.msgSuccess("更新成功");
            this.oilAndGunFormOpen = false;
          });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.card-table {
  // margin-top: 40px;
  background-color: #f8f8f8;

  .el-button {
    margin-bottom: 20px;
    margin-right: 20px;
  }
}

::v-deep .el-form-item {
  .el-form-item__label {
    padding: 0;
    margin: 0;
  }

  .el-button--cyan {
    margin-left: 20px;
  }
}
</style>
